import 'dart:convert' as convert;

import 'package:date_format/date_format.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/material.dart' as prefix0;
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:village_android/common/NoKeyboardEditableTextFocusNode.dart';
import 'package:village_android/component/jd_button.dart';
import 'package:village_android/component/member_header.dart';
import 'package:village_android/config/contants.dart';
import 'package:village_android/model/health_submit_model.dart';
import 'package:village_android/model/name_value_model.dart';
import 'package:village_android/model/order_model.dart';
import 'package:village_android/model/stats_model.dart';
import 'package:village_android/model/submit_record_model.dart';
import 'package:village_android/model/user_model.dart';
import 'package:village_android/pages/address/address_list.dart';
import 'package:village_android/pages/health/submit/submit_count.dart';
import 'package:village_android/pages/pay_page.dart';
import 'package:village_android/pages/user/user_list.dart';
import 'package:village_android/utils/common_utils.dart';
import 'package:village_android/utils/http_utlis.dart';

class HealthSubmitRecordPage extends StatefulWidget {
  @override
  _HealthSubmitRecordPageState createState() => _HealthSubmitRecordPageState();
}

class _HealthSubmitRecordPageState extends State<HealthSubmitRecordPage> {
  List healthRentalList = [];
  SubmitRecordModel submitRecordModel;

  @override
  void initState() {
    refreshData();
    super.initState();
  }

  refreshData() {
    getData();
  }

  getData() {
    HttpUtils.get("/sysConfig/list", data: {"dictTypeId": 11}, success: (data) {
      setState(() {
        healthRentalList = data;
        getRecordData();
      });
    }, error: (errorMsg) {
      print(errorMsg);
    });
  }

  getRecordData() {
    HttpUtils.get("/api/submitRecord/detail", data: {}, success: (data) {
      setState(() {
        submitRecordModel = SubmitRecordModel.fromJson(data);
        if (submitRecordModel != null) {
          var rentalData =
              convert.jsonDecode(submitRecordModel.healthRentalList);
          healthRentalList = rentalData["data"];
        }
      });
    }, error: (errorMsg) {
      print(errorMsg);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("申请记录详情"),
        actions: <Widget>[
          new RaisedButton(
              color: Colors.red,
              child: Text(
                "刷新",
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () {
                refreshData();
              }),
        ],
      ),
      body: ListView(
        scrollDirection: Axis.vertical,
        children: <Widget>[
          SizedBox(height: 25),
          Container(
            padding: EdgeInsets.only(left: 15.0),
            child: SizedBox(
              height: 40,
              width: double.infinity,
              child: Text(
                  submitRecordModel == null
                      ? '状态: ' + "未知"
                      : '状态: ' + (submitRecordModel.status == 0 ? "已审核" : "审核中"),
                  textAlign: TextAlign.left,
                  style: TextStyle(color: Colors.green)),
            ),
          ),
//            color: Colors.red,

          SizedBox(height: 25),
          AbsorbPointer(
            absorbing: false,
            child: ListView.builder(
                itemBuilder: (context, index) {
                  NameValueModel nameValue =
                      NameValueModel.fromJson(healthRentalList[index]);

                  nameValue.number =
                      nameValue.number != null ? nameValue.number : 0;
                  nameValue.value = int.parse(nameValue.value);
                  return _nameValueCell(nameValue);
                },
                shrinkWrap: true,
                physics: new NeverScrollableScrollPhysics(),
                itemCount: healthRentalList.length),
          ),
          Divider(height: 2.0, color: Colors.black38),
        ],
      ),
      bottomNavigationBar: BottomAppBar(
          child: Row(
        children: <Widget>[
          Expanded(
              child: JdButton(
            callBack: () {
              showAlertDialog(context);
            },
            text: "重新提交审核",
            color: Colors.red,
          )),
        ],
      )),
    );
  }

  //提交
  Future saveSubmit() async {
    submitRecordModel.status = 1;
    var params = submitRecordModel.toJson();
    Map rentalListData = new Map();
    rentalListData["data"] = this.healthRentalList;
    String rentalJson = convert.jsonEncode(rentalListData);
    params["healthRentalList"] = rentalJson;
    FormData formData = new FormData.from(params);
    var dio = new Dio();
    var response = await dio.post(BaseUrl.url + "/api/submitRecord/editItem",
        data: formData);
    print(response.data.toString());
    var data = response.data;
    if (data["code"] == 200 || data["code"] == 0) {
      CommonUtils.showToast(context, "提交成功");
      if (submitRecordModel != null) {
        refreshData();
      } else {
        Navigator.of(context).pop("insert");
      }
    } else {
      CommonUtils.showToast(context, "提交失败");
    }
  }

  void showAlertDialog(BuildContext context) {
    showDialog(
        context: context,
        builder: (_) => new AlertDialog(
                title: new Text("是否提交"),
                content: new Text(""),
                actions: <Widget>[
                  new FlatButton(
                    child: new Text("取消"),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                  new FlatButton(
                    child: new Text("确定"),
                    onPressed: () {
                      Navigator.of(context).pop();
                      saveSubmit();
                    },
                  )
                ]));
  }

  //独立Item
  Widget _nameValueCell(item) {
    return new GestureDetector(
//      onTap: () {onItemClick(item);},
      child: Container(
        height: ScreenUtil().setHeight(90),
        alignment: Alignment.center,
        padding: EdgeInsets.all(10.0),
        margin: EdgeInsets.all(10.0),
        color: Colors.white30,
        child: Row(
          children: <Widget>[
            Padding(padding: EdgeInsets.only(left: 15)),
            Expanded(
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  Container(
                    width: ScreenUtil.getInstance().setWidth(150),
                    child: Text(
                      item.name,
                      style: TextStyle(color: Colors.black, fontSize: 15.0),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  Expanded(
                    child: CountWidget(
                      count: item.number,
                      value: item.value,
                      targetId: item.name,
                      callBack: ((targetId, isIncrease) {
                        increaseOrReduceOperation(targetId, isIncrease);
                      }),
                    ),
                  ),
                  Padding(padding: EdgeInsets.only(right: 30)),
                  Container(
                    width: ScreenUtil.getInstance().setWidth(200),
                    child: Text(
                      "单价: " + item.value.toString() + "元/间",
                      style: TextStyle(color: Colors.black, fontSize: 15.0),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  Padding(padding: EdgeInsets.only(top: 2)),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 增加/减少商品数量
  increaseOrReduceOperation(String targetId, bool isIncrease) {
    int totalPrice = 0;

    for (int i = 0; i < healthRentalList.length; i++) {
      NameValueModel nameValue = NameValueModel.fromJson(healthRentalList[i]);
      if (nameValue.name == targetId) {
        if (isIncrease) {
          nameValue.number += 1;
        } else {
          nameValue.number -= 1;
          if (nameValue.number < 0) {
            nameValue.number = 0;
          }
        }
        healthRentalList[i] = nameValue.toJson();
      }
      totalPrice += int.parse(nameValue.value) * nameValue.number;
    }

    setState(() {
      healthRentalList = healthRentalList;
    });
  }
}
